//
//  ZXY_IMGFlashHelper.m
//  coreTextDemo
//
//  Created by 宇周 on 15/11/9.
//  Copyright © 2015年 宇周. All rights reserved.
//

#import "ZXY_IMGFlashHelper.h"
@interface ZXY_IMGFlashHelper()

@property(nonatomic , strong)UIView *flashV;
@property(nonatomic , strong)CABasicAnimation *basicAnimation;

@end
@implementation ZXY_IMGFlashHelper
- (id)init
{
    if(self == [super init])
    {
        self.widthOfMask = 20;
        self.edgeColor   = [[UIColor whiteColor] colorWithAlphaComponent:0.1];
        self.centerColor = [UIColor whiteColor];
    }
    return self;
}

- (void)startFlash
{
    if(self.flashV == nil)
    {
        NSException *vIsNill = [NSException exceptionWithName:@"nil View send to Flash" reason:@"the flashView could not be nil" userInfo:nil];
        @throw vIsNill;
    }
    CAGradientLayer *gradientMask = [CAGradientLayer layer];
    gradientMask.frame = self.flashV.bounds;
    
    CGFloat maskSize = self.widthOfMask / gradientMask.frame.size.width;
    NSArray *startLocations = @[@0 ,
                                [NSNumber numberWithFloat:maskSize / 2] ,
                                [NSNumber numberWithFloat:maskSize ]];
    NSArray *endLocations   = @[[NSNumber numberWithFloat:(1 - maskSize)] ,
                                [NSNumber numberWithFloat:(1 - maskSize / 2.0)] ,
                                @1];
    CGPoint startLocation    = CGPointMake(0 - maskSize * 2, 0);
    CGPoint endLocation      = CGPointMake(1 + maskSize* 2, 1);
    gradientMask.locations   = startLocations;
    gradientMask.startPoint  = startLocation ;
    gradientMask.endPoint    = endLocation;
    gradientMask.colors      = @[(id)self.edgeColor.CGColor ,
                                 (id)self.centerColor.CGColor ,
                                 (id)self.edgeColor.CGColor];
    self.flashV.layer.mask = gradientMask;
    self.basicAnimation = [CABasicAnimation animationWithKeyPath:@"locations"];
    self.basicAnimation.duration = 2;
    self.basicAnimation.repeatCount = HUGE_VALF;
    self.basicAnimation.fromValue = startLocations;
    self.basicAnimation.toValue   = endLocations;
    self.basicAnimation.delegate  = self;
    self.basicAnimation.autoreverses = YES;
    self.basicAnimation.removedOnCompletion = NO;
    [gradientMask addAnimation:self.basicAnimation forKey:@"ZXY_IMGFlashHelper_Key"];
    
}

- (void)stopFlash
{
    if(self.flashV && self.flashV.layer.mask)
    {
        [self.flashV.layer.mask removeAnimationForKey:@"ZXY_IMGFlashHelper_Key"];
        self.flashV.layer.mask = nil;
        self.basicAnimation = nil;
    }
}

- (void)setFlashImg:(UIView *)flashView
{
    self.flashV = flashView;
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    if(anim == self.basicAnimation)
    {
        [self stopFlash];
    }
}

@end
